package com.banyechan.lingo_words.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class ExcleUtil {


    /**
     * 导出文件
     * @param data      数据
     * @param fieldMap  表头
     * @param fileName 文件名
     * @param response
     */
    public static void exportExcel(List data, Map<String, String> fieldMap, String fileName, HttpServletResponse response) {
        ServletOutputStream out = null;
        ExcelWriter writer = null;
        try {
            writer = ExcelUtil.getWriter(true);
            writer.renameSheet(fileName);
            if(CollectionUtils.isNotEmpty(fieldMap)){
                for(String tem : fieldMap.keySet()){
                    writer.addHeaderAlias(tem, fieldMap.get(tem));
                }
            }
            writer.setOnlyAlias(true);
            writer.merge(fieldMap.size() - 1, fileName);//合并单元格

            writer.write(data, true);
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
            response.setCharacterEncoding("utf-8");
            out=response.getOutputStream();
            writer.flush(out, true);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    IoUtil.close(out);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (writer != null){
                try {
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }



}
